﻿using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.UI;
using Camc.Quality.DataDictionary;
using Camc.Quality.Materials;
using Camc.Quality.Materials.Dto;
using Camc.Quality.ProductionPlan;
using Camc.Quality.StoreManagement.Dto;
using Camc.Quality.StoreManagement.StoragePut;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Camc.Quality.StoreManagement
{
    public class StoreFunctionsAppService : QualityAppServiceBase
    {
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        private readonly IRepository<MaterialsDesc, Guid> _materiaDesclsRepository;
        private readonly IRepository<MaterialsNode, Guid> _materialsNodeRepository;
        private readonly IRepository<StoreContent, Guid> _storeContentrepository;
        private readonly IRepository<MaterialsContent, Guid> _materialsContentRepository;
        private readonly IRepository<StorePutContent, Guid> _storePutContentRepository;
        private readonly IRepository<MakeTask, Guid> _makeTaskRepository;
        private readonly IRepository<StandardDrawingNo, Guid> _standardDrawingNoRepository;
        public StoreFunctionsAppService(IRepository<Sys_Code, Guid> sysCodeRepository,
            IRepository<MaterialsDesc, Guid> materiaDesclsRepository,
            IRepository<MaterialsNode, Guid> materialsNodeRepository,
            IRepository<StoreContent, Guid> storeContentrepository,
            IRepository<MaterialsContent, Guid> materialsContentRepository,
            IRepository<StorePutContent, Guid> storePutContentRepository,
            IRepository<MakeTask, Guid> makeTaskRepository,
            IRepository<StandardDrawingNo, Guid> standardDrawingNoRepository
            )
        {
            _sysCodeRepository = sysCodeRepository;
            _materiaDesclsRepository = materiaDesclsRepository;
            _materialsNodeRepository = materialsNodeRepository;
            _storeContentrepository = storeContentrepository;
            _materialsContentRepository = materialsContentRepository;
            _storePutContentRepository = storePutContentRepository;
            _makeTaskRepository = makeTaskRepository;
            _standardDrawingNoRepository = standardDrawingNoRepository;
        }
        /// <summary>
        /// 获取单位
        /// </summary>
        /// <returns></returns>
        public async Task<List<MaterialsOtherDto>> GetCodeDropList()
        {
            var queryCode = from sc in _sysCodeRepository.GetAll().Where(s => s.IsUsed == 1)
                            join scc in _sysCodeRepository.GetAll()
                            on sc.PPtr equals scc.Id
                            where scc.Description == "单位"
                            select new MaterialsOtherDto
                            {
                                label = sc.Description,
                                value = sc.Id
                            };
            if (queryCode.Count() > 0)
            {
                return queryCode.ToList();
            }
            return new List<MaterialsOtherDto>();
        }
        /// <summary>
        /// 获取储位
        public async Task<List<MaterialsOtherDto>> GetBinLocationDropList()
        {
            var queryCode = from sc in _sysCodeRepository.GetAll().Where(s => s.IsUsed == 1)
                            join scc in _sysCodeRepository.GetAll()
                            on sc.PPtr equals scc.Id
                            where scc.Description == "储位"
                            select new MaterialsOtherDto
                            {
                                label = sc.Description,
                                value = sc.Id
                            };
            if (queryCode.Count() > 0)
            {
                return queryCode.ToList();
            }
            return new List<MaterialsOtherDto>();
        }
        /// <summary>
        /// 获取物料类型
        /// </summary>
        /// <returns></returns>
        public List<MaterialsOtherDto> GetMaterialsTypeDropList()
        {
            var queryMaterialsType = from queryMaterialstTypeData in _materialsNodeRepository.GetAll()
                                     join queryMaterialsDesc in _materiaDesclsRepository.GetAll() on queryMaterialstTypeData.ParentCode equals
                                     queryMaterialsDesc.Id
                                     select new MaterialsOtherDto
                                     {
                                         label = queryMaterialstTypeData.MaterialTypeName,
                                         value = queryMaterialstTypeData.Id
                                     };
            if (queryMaterialsType.Count() > 0)
            {
                return queryMaterialsType.ToList();
            }
            return new List<MaterialsOtherDto>();
        }
        /// <summary>
        /// 获取物料细类
        /// </summary>
        /// <returns></returns>
        public List<MaterialsOtherDto> GetSegmentationMaterialsTypeDropList(Guid id)
        {
            var queryMaterialsNodeList = _materialsNodeRepository.FirstOrDefault(t => t.Id == id);
            string materialstTypeCode = queryMaterialsNodeList.MaterialsTypeCode;
            if (queryMaterialsNodeList.MaterialsTypeCode.IndexOf('_') > 0 && !string.IsNullOrEmpty(queryMaterialsNodeList.MaterialsTypeCode))
            {
                string[] sArray = queryMaterialsNodeList.MaterialsTypeCode.Split("_");
                materialstTypeCode = sArray[0];
            }
            var queryMaterialsType = from queryMaterialstTypeData in _materialsNodeRepository.GetAll().Where(t => t.MaterialsTypeCode.StartsWith(materialstTypeCode))
                                     select new MaterialsOtherDto
                                     {
                                         label = queryMaterialstTypeData.MaterialTypeName,
                                         value = queryMaterialstTypeData.Id
                                     };
            if (queryMaterialsType.Count() > 0)
            {
                return queryMaterialsType.ToList();
            }
            return new List<MaterialsOtherDto>();
        }
        /// <summary>
        /// 获取仓库
        /// </summary>
        /// <returns></returns>
        public List<MaterialsOtherDto> GetStoreDropList()
        {
            var storeContent = _storeContentrepository.GetAll().Where(s => s.StoreUse == StoreEnum.StoreIsUse.是);
            var query = (from sc in storeContent
                         select new MaterialsOtherDto
                         {
                             label = sc.StroeName,
                             value = sc.Id
                         }).ToList();
            if (query.Count() > 0)
            {
                return query;
            }
            return new List<MaterialsOtherDto>();
        }
        /// <summary>
        /// 型号下拉列表 
        /// </summary>
        /// <returns></returns>
        public List<StoreDropListOutDto> GetRocketModeDropList()
        {

            var queryCode = from sc in _sysCodeRepository.GetAll().Where(s => s.IsUsed == 1)
                            join scc in _sysCodeRepository.GetAll()
                            on sc.PPtr equals scc.Id
                            where scc.Description == "型号"
                            select new StoreDropListOutDto
                            {
                                Label = sc.Description,
                                Value = sc.Id.ToString()
                            };
            if (queryCode.Count() > 0)
            {
                return queryCode.Distinct().OrderBy(s => s.Label).ToList();
            }
            return new List<StoreDropListOutDto>();
        }
        /// <summary>
        /// 发次下拉列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<StoreDropListOutDto> GetRocketLotNoDropList(List<StoreDropListOutDto> input)
        {
            if (input.Count() <= 0)
            {
                return null;
            }
            List<StoreDropListOutDto> storeDropListOutDtos = new List<StoreDropListOutDto>();
            //型号里包含“系列”时，关联发次为全发次
            var lable = string.Join(",", input.Select(d => d.Label));
            var index = lable.IndexOf("系列");
            if(index>0)
            {
                var queryCode = from sc in _sysCodeRepository.GetAll().Where(s => s.IsUsed == 1)
                                join scc in _sysCodeRepository.GetAll()
                                on sc.PPtr equals scc.Id
                                where (scc.Description == "发次" && sc.Description == "全发次")
                                select new StoreDropListOutDto
                                {
                                    Label = sc.Description,
                                    Value = sc.Id.ToString()
                                };
                StoreDropListOutDto storeDropListOutDto = new StoreDropListOutDto();
                foreach (var item in queryCode)
                {
                    storeDropListOutDto.Label = item.Label;
                    storeDropListOutDto.Value = item.Value;
                    storeDropListOutDtos.Add(storeDropListOutDto);
                }
                return storeDropListOutDtos;
            }
            ////型号里不包含“系列”时，根据生产任务关联发次
            var value = string.Join(",", input.Select(d => d.Value));
            var makeModel = _makeTaskRepository.GetAll().Where(d => value.Contains(d.ModelId.ToString()));
            if (makeModel.Count() > 0)
            {
                var modelIdList = makeModel.Select(d => d.LotNoId);
                var query = (from sc in _sysCodeRepository.GetAll().Where(s => s.IsUsed == 1)
                             join scc in _sysCodeRepository.GetAll()
                             on sc.PPtr equals scc.Id
                             join mm in modelIdList on sc.Id equals mm
                             select new
                             {
                                 Label = sc.Description,
                                 Value = sc.Id.ToString()
                             }).Distinct().OrderBy(s => s.Label).ToList();
                foreach (var item in query)
                {
                    StoreDropListOutDto storeDropListOutDto = new StoreDropListOutDto();
                    storeDropListOutDto.Label = item.Label;
                    storeDropListOutDto.Value = item.Value;
                    storeDropListOutDtos.Add(storeDropListOutDto);
                }
                //storeDropListOutDtos = query.Distinct().ToList();
                return storeDropListOutDtos;
            }
            else
            {
                return new List<StoreDropListOutDto>();
            }

        }
        /// <summary>
        /// 规格下拉列表  
        /// </summary>
        /// <returns></returns>
        public List<StoreDropListOutDto> GetMaterialsContentsModelList(string productDrawingNo)
        {
            if (!string.IsNullOrEmpty(productDrawingNo))
            {
                var year = productDrawingNo.Substring(productDrawingNo.LastIndexOf("-") + 1);
                //校验年代号(2位或者4位数字)
                if (!string.IsNullOrEmpty(year))
                {
                    int yearCount = year.Length;
                    if (yearCount == 2 || yearCount == 4)
                    {
                        try
                        {
                            int.Parse(year);
                            productDrawingNo = productDrawingNo.Substring(0, productDrawingNo.LastIndexOf("-"));
                        }
                        catch
                        {
                        }
                    }
                }
                var modelList = _materialsContentRepository.GetAll().Where(s => s.MaterialNo.Contains(productDrawingNo));//add 11/30
                var query = modelList.Select(p => p.Model).Distinct().Where(d => !string.IsNullOrEmpty(d)).ToList();
                var storeDropList = from q in query
                                    select new StoreDropListOutDto
                                    {
                                        Label = q,
                                        Value = q
                                    };
                if (storeDropList.Count() > 0)
                {
                    return storeDropList.ToList();
                }
            }
            return new List<StoreDropListOutDto>();
        }
        /// <summary>
        /// 放行单号模糊查询
        /// </summary>
        /// <returns></returns>
        public List<string> GetReleaseOrderList()
        {
            return _storePutContentRepository.GetAll().Select(p => p.ReleaseOrder).Distinct().Where(d => d != null).ToList();
        }
        /// <summary>
        /// 产品名称列表
        /// </summary>
        /// <param name="productDrawingNoStr"></param>
        /// <param name="modelStr"></param>
        /// <returns></returns>
        public List<string> GetProductNameDropList(string productDrawingNoStr)
        {
            var productNamrList = _materialsContentRepository.GetAll().Where(s => s.MaterialProperty == 3);
            if (!string.IsNullOrEmpty(productDrawingNoStr))
            {
                productNamrList = productNamrList.Where(p => p.MaterialNo == productDrawingNoStr);
                if (productNamrList == null)
                {
                    return null;
                }                                           
            }
            return productNamrList.Select(s => s.MaterialName).Distinct().ToList();
        }
        /// <summary>
        /// 标准件（包含规格、年代号）解析接口
        /// <param name="productCode"></param>
        /// <returns></returns>
        public StandardOutputDto GetStandardDrawingNoDispose(string productCode)
        {
            StandardOutputDto standardOutputDto = new StandardOutputDto();
            //和标准件图号库对比
            var code = _standardDrawingNoRepository.FirstOrDefault(s => productCode.Contains(s.Code));
            if (code != null)
            {
                standardOutputDto.IsStandar = 1;
                //将连续的多个空格替换成一个空格,并去掉前后多余的空格
                Regex replaceSpace = new Regex(@"\s{1,}", RegexOptions.IgnoreCase);
                var disposeCode = replaceSpace.Replace(productCode, " ").Trim();
                string keyWord = " ";
                int index = 0;
                int count = 0;
                //计算空格的数量
                while ((index = disposeCode.IndexOf(keyWord, index)) != -1)
                {
                    count++;
                    index += keyWord.Length;
                }
                if (count > 2) throw new UserFriendlyException("处理时出错，请检查物料代号是否正确");
                //字符串里有两个空格时，最后一个空格后面的字符串没有用去掉
                if (count == 2)
                {
                    //去掉图号最后面的不要的字段
                    disposeCode = disposeCode.Substring(0, disposeCode.LastIndexOf(" ")).Trim();
                    //字符串剩余空格=1
                    count -= 1;
                }
                //如果规格在图号左边
                if (disposeCode.ToLower().StartsWith(code.Code.ToLower()) == false)
                {
                    //分割出规格
                    var array = disposeCode.Split(code.Code);
                    standardOutputDto.Module = array[0].Trim().Replace("X", "x").Replace("*", "x").Replace("×", "x").ToUpper();
                    disposeCode = code.Code + array[1].Trim();
                    count = 0;
                    index = 0;
                    //计算空格的数量
                    while ((index = disposeCode.IndexOf(keyWord, index)) != -1)
                    {
                        count++;
                        index = index + keyWord.Length;
                    }
                    if (count == 1)
                    {
                        //去掉图号最后面的不要的字段
                        disposeCode = disposeCode.Substring(0, disposeCode.LastIndexOf(" ")).Trim();
                    }
                    //截取年代号
                    var year = disposeCode.Substring(disposeCode.LastIndexOf("-") + 1);
                    //校验年代号(2位或者4位数字)
                    if (!string.IsNullOrEmpty(year))
                    {
                        int yearCount = year.Length;
                        if (yearCount == 2 || yearCount == 4)
                        {
                            try
                            {
                                int.Parse(year);
                                standardOutputDto.YearNo = year;
                                //剩下的字符串：1:规格+" "+图号 2:规格+图号 3:图号+" "+规格 4:图号
                                disposeCode = disposeCode.Substring(0, disposeCode.LastIndexOf("-"));
                            }
                            catch
                            {
                            }
                        }
                    }
                    standardOutputDto.ProductDrawingNo = disposeCode.ToUpper();
                }
                //如果图号在最左边
                else
                {
                    //空格数量为1时,字符串里包含规格
                    if (count == 1)
                    {
                        //计算年代号和规格位置
                        int yearindex = disposeCode.IndexOf("-");
                        int moduleindex = disposeCode.IndexOf(" ");
                        //年代号在规格右边
                        if (yearindex > moduleindex)
                        {
                            //截取年代号
                            var year = disposeCode.Substring(disposeCode.LastIndexOf("-") + 1);
                            //校验年代号(2位或者4位数字)
                            if (!string.IsNullOrEmpty(year))
                            {
                                int yearCount = year.Length;
                                if (yearCount == 2 || yearCount == 4)
                                {
                                    try
                                    {
                                        int.Parse(year);
                                        standardOutputDto.YearNo = year;
                                        //剩下的字符串:1:规格+" "+图号 2:规格+图号 3:图号+" "+规格 4:图号
                                        disposeCode = disposeCode.Substring(0, disposeCode.LastIndexOf("-"));
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                            //剩余字符串：图号+" "+规格
                            var array = disposeCode.Split(" ");
                            standardOutputDto.ProductDrawingNo = array[0].ToUpper();
                            standardOutputDto.Module = array[1].Replace("X", "x").Replace("*", "x").Replace("×", "x").ToUpper();
                        }
                        //年代号在规格左边
                        else
                        {
                            var array = disposeCode.Split(" ");
                            standardOutputDto.Module = array[1].Replace("X", "x").Replace("*", "x").Replace("×", "x");
                            disposeCode = array[0];
                            //截取年代号
                            var year = disposeCode.Substring(disposeCode.LastIndexOf("-") + 1);
                            //校验年代号(2位或者4位数字)
                            if (!string.IsNullOrEmpty(year))
                            {
                                int yearCount = year.Length;
                                if (yearCount == 2 || yearCount == 4)
                                {
                                    try
                                    {
                                        int.Parse(year);
                                        standardOutputDto.YearNo = year;
                                        //剩下的字符串：1:规格+" "+图号 2:规格+图号 3:图号+" "+规格 4:图号
                                        disposeCode = disposeCode.Substring(0, disposeCode.LastIndexOf("-"));
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                            standardOutputDto.ProductDrawingNo = disposeCode.ToUpper();
                        }
                    }
                    //空格数量为0时,字符串里不包含规格
                    else
                    {
                        //截取年代号
                        var year = disposeCode.Substring(disposeCode.LastIndexOf("-") + 1);
                        //校验年代号(2位或者4位数字)
                        if (!string.IsNullOrEmpty(year))
                        {
                            int yearCount = year.Length;
                            if (yearCount == 2 || yearCount == 4)
                            {
                                try
                                {
                                    int.Parse(year);
                                    standardOutputDto.YearNo = year;
                                    //剩下的字符串：1:规格+" "+图号 2:规格+图号 3:图号+" "+规格 4:图号
                                    disposeCode = disposeCode.Substring(0, disposeCode.LastIndexOf("-"));
                                }
                                catch
                                {
                                }
                            }
                        }
                        standardOutputDto.ProductDrawingNo = disposeCode.ToUpper();
                    }
                }
            }
            else
            {
                standardOutputDto.IsStandar = 0;
                standardOutputDto.ProductDrawingNo = productCode;
            }
            return standardOutputDto;
        }
    }
}
